package com.nkzy.controller;

import com.nkzy.pojo.Result;
import com.nkzy.pojo.User;
import com.nkzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
//RestFul风格:在类中的注解@RequestMapping("/user")，加上s如("/users")
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    // 插入用户
    @PostMapping
    public Result<Integer> insertUser(@RequestBody User user) {
        int result = userService.insertUser(user);
        return result > 0 ? Result.ok(result) : Result.fail("插入用户失败");
    }

    // 根据ID删除用户
    //{id}表示占位符，是RestFul风格的使用
    @DeleteMapping("/{id}")
    public Result<Integer> deleteUserById(@PathVariable Long id) {
        int result = userService.deleteUserById(id);
        return result > 0 ? Result.ok(result) : Result.fail("删除用户失败");
    }

    // 更新用户信息
    @PutMapping
    public Result<Integer> updateUser(@RequestBody User user) {
        int result = userService.updateUser(user);
        return result > 0 ? Result.ok(result) : Result.fail("更新用户失败");
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public Result<User> selectUserById(@PathVariable Long id) {
        User user = userService.selectUserById(id);
        return user != null ? Result.ok(user) : Result.fail("查询用户失败");
    }

    // 根据多个ID查询用户
    @GetMapping("/ids")
    public Result<List<User>> selectUsersByIds(@RequestParam List<Long> ids) {
        List<User> users = userService.selectUsersByIds(ids);
        return users != null && !users.isEmpty() ? Result.ok(users) : Result.fail("查询用户失败");
    }

    // 查询所有用户
    @GetMapping("/list")
    public Result<List<User>> selectAllUsers() {
        List<User> users = userService.selectAllUsers();
        return users != null && !users.isEmpty() ? Result.ok(users) : Result.fail("查询用户失败");
    }
}